var express = require('express')
var app = express()
const ApiList = require('./route/index')
const port = 9999;
//设置跨域访问
app.all("*",function(req,res,next){
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin","*");
    //允许的header类型
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else
        next();
})

const ResponseFn = (fn,req)=>{
    return new Promise((resolve)=>{
        setTimeout(()=>{
            resolve(fn(req))
        },1000)
    })
}

for(let i = 0;i<ApiList.length;i++){
    let item = ApiList[i]
    console.log(item)
    app[item.method](item.url,async(req,res)=>{
        let data = await ResponseFn(item.response,req)
        res.json(data)
    })
}

app.get('/api/hah',(req,res)=>{
    res.json({
        data:0
    })
})

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});